package com.anonymous.community.ui.home;

import android.animation.ValueAnimator;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.widget.ViewPager2;

import com.anonymous.community.R;
import com.anonymous.community.databinding.FragmentHomeBinding;
import com.anonymous.community.ui.base.BaseFragment;
import com.anonymous.community.utils.TokenManager;

public class HomeFragment extends BaseFragment {

    private FragmentHomeBinding binding;
    private TokenManager tokenManager;
    private HomePagerAdapter pagerAdapter;
    private TextView tabFollow, tabRecommend, tabWelfare, tabLatest;
    private View tabIndicator;
    private ViewPager2 viewPager;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // 初始化TokenManager
        tokenManager = new TokenManager(requireContext());

        // 初始化视图
        initViews();
        
        // 设置ViewPager2和自定义标签导航
        setupViewPager();
        setupCustomTabs();
        
        return root;
    }

    private void initViews() {
        viewPager = binding.viewPager;
        
        // 获取自定义标签导航栏中的视图
        tabFollow = binding.customTabNavigation.tabFollow;
        tabRecommend = binding.customTabNavigation.tabRecommend;
        tabWelfare = binding.customTabNavigation.tabWelfare;
        tabLatest = binding.customTabNavigation.tabLatest;
        tabIndicator = binding.customTabNavigation.tabIndicator;
    }

    private void setupViewPager() {
        // 创建适配器
        pagerAdapter = new HomePagerAdapter(requireActivity());
        
        // 设置适配器
        viewPager.setAdapter(pagerAdapter);
        
        // 监听页面切换，包括滑动过程中的实时位置变化
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                // 实时更新指示器位置，实现跟随滑动的流畅效果
                updateIndicatorPositionWithOffset(position, positionOffset);
            }
            
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                updateTabSelection(position);
            }
        });
    }

    private void setupCustomTabs() {
        // 设置标签点击事件
        tabFollow.setOnClickListener(v -> {
            viewPager.setCurrentItem(0, true);
        });
        
        tabRecommend.setOnClickListener(v -> {
            viewPager.setCurrentItem(1, true);
        });
        
        tabWelfare.setOnClickListener(v -> {
            viewPager.setCurrentItem(2, true);
        });
        
        tabLatest.setOnClickListener(v -> {
            viewPager.setCurrentItem(3, true);
        });
        
        // 初始化第二个标签（推荐）为选中状态
        updateTabSelection(1);
    }

    private void updateTabSelection(int position) {
        // 重置所有标签样式
        resetTabStyles();
        
        // 设置选中标签样式 - 使用黑色，保持相同字体大小避免文字跳动
        switch (position) {
            case 0:
                tabFollow.setTextColor(0xFF000000); // 黑色
                tabFollow.getPaint().setFakeBoldText(true);
                break;
            case 1:
                tabRecommend.setTextColor(0xFF000000); // 黑色
                tabRecommend.getPaint().setFakeBoldText(true);
                break;
            case 2:
                tabWelfare.setTextColor(0xFF000000); // 黑色
                tabWelfare.getPaint().setFakeBoldText(true);
                break;
            case 3:
                tabLatest.setTextColor(0xFF000000); // 黑色
                tabLatest.getPaint().setFakeBoldText(true);
                break;
        }
        
        // 更新指示器位置（这里简化处理，实际可以添加动画效果）
        updateIndicatorPosition(position);
    }

    private void resetTabStyles() {
        int normalColor = 0xFF666666; // 深灰色，与黑色形成对比
        
        tabFollow.setTextColor(normalColor);
        tabFollow.getPaint().setFakeBoldText(false);
        
        tabRecommend.setTextColor(normalColor);
        tabRecommend.getPaint().setFakeBoldText(false);
        
        tabWelfare.setTextColor(normalColor);
        tabWelfare.getPaint().setFakeBoldText(false);
        
        tabLatest.setTextColor(normalColor);
        tabLatest.getPaint().setFakeBoldText(false);
    }

    private void updateIndicatorPosition(int position) {
        ViewGroup.LayoutParams params = tabIndicator.getLayoutParams();
        if (params instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams marginParams = (ViewGroup.MarginLayoutParams) params;
            int screenWidth = getResources().getDisplayMetrics().widthPixels;
            
            // 标签导航区域占屏幕2/3宽度（权重2:1），左对齐，无左侧空白
            int tabAreaWidth = screenWidth * 2 / 3; // 标签区域宽度
            
            // 计算目标margin和指示器宽度
            int targetMargin = calculateTabIndicatorMargin(position, tabAreaWidth);
            
            // 获取当前选中标签并动态调整指示器宽度
            TextView currentTab = getTabByPosition(position);
            if (currentTab != null) {
                int textWidth = (int) currentTab.getPaint().measureText(currentTab.getText().toString());
                float density = getResources().getDisplayMetrics().density;
                int indicatorWidthPx = Math.max((int)(textWidth * 0.8f), (int)(16 * density)); // 最小16dp
                
                // 更新指示器宽度
                params.width = indicatorWidthPx;
                
                // 使用加速减速插值器实现更自然的滑动动画
                ValueAnimator animator = ValueAnimator.ofInt(marginParams.leftMargin, targetMargin);
                animator.setDuration(250); // 缩短动画时长，提升响应速度
                animator.setInterpolator(new AccelerateDecelerateInterpolator()); // 自然的加速减速效果
                animator.addUpdateListener(animation -> {
                    marginParams.leftMargin = (int) animation.getAnimatedValue();
                    tabIndicator.setLayoutParams(marginParams);
                });
                animator.start();
            }
        }
    }
    
    /**
     * 根据ViewPager滑动偏移量实时更新指示器位置
     * @param position 当前页面位置
     * @param positionOffset 滑动偏移量 (0.0 - 1.0)
     */
    private void updateIndicatorPositionWithOffset(int position, float positionOffset) {
        ViewGroup.LayoutParams params = tabIndicator.getLayoutParams();
        if (params instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams marginParams = (ViewGroup.MarginLayoutParams) params;
            int screenWidth = getResources().getDisplayMetrics().widthPixels;
            
            // 标签导航区域占屏幕2/3宽度（权重2:1），左对齐，无左侧空白
            int tabAreaWidth = screenWidth * 2 / 3; // 标签区域宽度
            
            // 计算当前位置和下一个位置的margin值
            int currentMargin = calculateTabIndicatorMargin(position, tabAreaWidth);
            int nextMargin = calculateTabIndicatorMargin(position + 1, tabAreaWidth);
            
            // 根据滑动偏移量线性插值计算实际margin
            int actualMargin = (int) (currentMargin + (nextMargin - currentMargin) * positionOffset);
            
            // 动态调整指示器宽度
            TextView currentTab = getTabByPosition(position);
            TextView nextTab = getTabByPosition(position + 1);
            if (currentTab != null && nextTab != null) {
                int currentTextWidth = (int) currentTab.getPaint().measureText(currentTab.getText().toString());
                int nextTextWidth = (int) nextTab.getPaint().measureText(nextTab.getText().toString());
                float density = getResources().getDisplayMetrics().density;
                
                int currentIndicatorWidth = Math.max((int)(currentTextWidth * 0.8f), (int)(16 * density));
                int nextIndicatorWidth = Math.max((int)(nextTextWidth * 0.8f), (int)(16 * density));
                
                // 根据滑动偏移量插值计算指示器宽度
                int actualWidth = (int) (currentIndicatorWidth + (nextIndicatorWidth - currentIndicatorWidth) * positionOffset);
                params.width = actualWidth;
            }
            
            // 直接设置margin，无动画，实现跟随滑动的实时效果
            marginParams.leftMargin = actualMargin;
            tabIndicator.setLayoutParams(marginParams);
        }
    }

    /**
     * 计算指定位置标签的指示器margin值
     */
    private int calculateTabIndicatorMargin(int position, int tabAreaWidth) {
        if (position < 0 || position > 3) return 0;
        
        // 计算标签在容器中的起始位置
        int tabStartPosition = 0;
        for (int i = 0; i < position; i++) {
            TextView tab = getTabByPosition(i);
            if (tab != null) {
                if (i == 3) { // "小黑屋"标签使用wrap_content
                    int tabTextWidth = (int) tab.getPaint().measureText(tab.getText().toString());
                    int paddingHorizontal = tab.getPaddingStart() + tab.getPaddingEnd();
                    tabStartPosition += tabTextWidth + paddingHorizontal;
                } else {
                    tabStartPosition += tabAreaWidth / 4; // 其他标签平均分配
                }
            }
        }
        
        // 计算指示器的位置：文字居中对齐
        TextView currentTab = getTabByPosition(position);
        if (currentTab != null) {
            // 测量文字实际宽度并动态调整指示器宽度
            int textWidth = (int) currentTab.getPaint().measureText(currentTab.getText().toString());
            float density = getResources().getDisplayMetrics().density;
            int indicatorWidthPx = Math.max((int)(textWidth * 0.8f), (int)(16 * density)); // 最小16dp
            
            if (position == 3) { // "小黑屋"标签
                int paddingHorizontal = currentTab.getPaddingStart() + currentTab.getPaddingEnd();
                int tabTotalWidth = textWidth + paddingHorizontal;
                return tabStartPosition + (tabTotalWidth - indicatorWidthPx) / 2;
            } else {
                int tabWidth = tabAreaWidth / 4;
                return tabStartPosition + (tabWidth - indicatorWidthPx) / 2;
            }
        }
        
        return tabStartPosition;
    }

    /**
     * 根据位置获取对应的标签TextView
     */
    private TextView getTabByPosition(int position) {
        switch (position) {
            case 0:
                return tabFollow;
            case 1:
                return tabRecommend;
            case 2:
                return tabWelfare;
            case 3:
                return tabLatest;
            default:
                return null;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    protected String getPageName() {
        return "首页";
    }
}